<template>
	<view class="container">
		<u-navbar
			title="授权登录"
			:isBack="false"
		></u-navbar>
		<view class="content flex_clm justify-start align-center">
			<image 
				style="width: 152rpx;height: 152rpx;margin-top: 122rpx;" 
				src="http://shejihm.oss-cn-beijing.aliyuncs.com/202404081716451712567805660400ddad8.png" 
				mode=""
			></image>
			<image
				style="width: 264rpx;height: 83rpx;margin-top: 32rpx;" 
				src="http://shejihm.oss-cn-beijing.aliyuncs.com/2024040916032917126498092533f183acd.png" 
				mode=""
			></image>
			<view 
				class="btn flex justify-center align-center" 
				@click="selectBtn ? ToLogin() : conShow = true"
			>
				{{ selectBtn ? '一键登录' : '请先同意用户协议' }}
			</view>
			<view
				class="argeement flex justify-start align-start" 
				@tap="changeSelect"
			>
				<image 
					style="flex-shrink: 0;position: relative;top: 6rpx;" 
					:src="selectBtn ? '/static/images/icon_add_select.png' : '/static/images/icon_add_default.png'" 
					mode=""
				></image>
				<view class="texts">
					<text>我已认真阅读并同意</text>
					<text @tap.stop="ToAgreement('用户须知及使用协议', 'userAgreement')">《用户须知及使用协议》、</text>
					<text @tap.stop="ToAgreement('隐私政策', 'PrivacyPolicy')">《隐私政策》</text>
				</view>
			</view>
		</view>
		
		
		
		<!-- 登录弹框 -->
		<u-popup 
			v-model="showLogin" 
			mode="bottom" 
			border-radius="25" 
			@close="handleCancel()"
		>
			<view style="padding: 40rpx 30rpx;min-width: 300rpx;">
				<h2 style="font-weight: bold;">申请获取您的头像、昵称</h2>
				<u-form :model="queryParams" ref="form1">
					<u-form-item label="头像:" prop="avatar">
						<view style="width: 100%;" class="flex justify-end">
							<button open-type="chooseAvatar" @chooseavatar="onChooseAvatar" class="avatar-wrapper">
								<image :src="queryParams.avatar" mode=""
									style="width: 60rpx;height: 60rpx;border-radius: 10rpx;background-color: #eee;">
								</image>
							</button>
						</view>
					</u-form-item>
					<u-form-item label="昵称:" prop="nickname">
						<u-input 
							v-model="queryParams.nickname"
							type="nickname" 
							input-align="right" 
							placeholder="请输入" 
							@blur="(e)=>{ queryParams.nickname = e }"
						/>
					</u-form-item>
				</u-form>
				<view class="flex justify-around" style="margin-top: 40rpx;">
					<u-button type="default" size="medium" @click.stop="handleCancel()">关闭</u-button>
					<view style="position: relative;">
						<view 
							style="position: absolute; top: 0; left: 0; right: 0; bottom: 0;background-color: yellow;z-index: 9999;background-color: rgba(0,0,0,0);"
							@tap.stop="handleWarning"
							v-if="isNull"
						></view>
						<u-button
							type="success" 
							size="medium"
							open-type="getPhoneNumber" 
							@getphonenumber="getPhoneNumber"
						>允许</u-button>
					</view>
				</view>
			</view>
		</u-popup>
		<u-modal
			v-model="conShow" 
			content="是否已查看并同意用户协议内容？" 
			@confirm="selectBtn = true"
			:show-cancel-button="true"
			confirmText="同意"
			cancelText="再看看"
		></u-modal>
	</view>
</template>

<script setup>
	import { getCurrentInstance, onMounted, ref, computed } from 'vue';
	import { uploadFile } from '@/utils/uploadFile.js';
	import { onLoad, onUnload, onShow } from "@dcloudio/uni-app"
	import {useMainStore} from '@/store/index.js'
	const mainStore = useMainStore()
	const {proxy} = getCurrentInstance()
	const showLogin = ref(false)
	const conShow = ref(false)
	const selectBtn = ref(false)
	const queryParams = ref({
		avatar: '/static/images/null_avatar.jpg',
		nickname: '',
		encryptedData: '',
		iv: '',
		sessionKey:'',
		openid:'',
	})
	
	const isNull = computed(()=>{
		return !queryParams.value.avatar || !queryParams.value.nickname || queryParams.value.avatar=='/static/images/null_avatar.jpg'
	})
	// 切换是否选中
	function changeSelect() {
		selectBtn.value = !selectBtn.value
	}
	// 调登录接口
	function loginApi(query){
		proxy.api.login(query).then(res=>{
			
			// 设置token
			uni.setStorageSync('TOKEN', res.data.data.token)
			// currentToken.value = res.data.data.token
			// 获取用户信息
			mainStore.handleGetUserInfo()
			setTimeout(()=>{
				// uni.switchTab({
				// 	url:"/pages/my/my"
				// })
				uni.navigateBack({
					delta: 1
				})
				proxy.tui.toast('登录成功')
			}, 400)
		})
	}
	// 未填用户名和头像校验
	function handleWarning(){
		proxy.tui.toast("请将昵称和头像填写完整")
	}
	// 获取用户头像
	function onChooseAvatar(e) {
		uploadFile({
			filePath: e.detail.avatarUrl,
			dir: 'image/',
			name: 'avatar'
		}).then(result => {
			queryParams.value.avatar = result
		}).catch(err => {
			console.log('werr',err)
			proxy.tui.toast('图片上传失败!请重新上传');
		});
		// queryParams.value.avatar = e.detail.avatarUrl
	}
	// 关闭登录弹框
	function handleCancel(){
		showLogin.value = false
		queryParams.value = {
			avatar: '/static/images/null_avatar.jpg',
			nickname: '',
			encryptedData: '',
			iv: '',
			sessionKey:'',
			openid: '',
		}
	}
	// 跳转到协议
	function ToAgreement(title, code){
		uni.navigateTo({
			url:`/pages/agreement/agreement?pageTitle=${title}&code=${code}`
		})
	}
	// 获取手机号
	function getPhoneNumber(e) {
		console.log('回调', e)
		if(e.detail.errMsg == 'getPhoneNumber:ok'){
			queryParams.value.encryptedData = e.detail.encryptedData,
			queryParams.value.iv = e.detail.iv,
			uni.login({
				provider: 'weixin',
				success: res => {
					// 通过参数获取sessionKey，然后调用登录接口注册账号
					proxy.api.initWxLogin({code: res.code}).then(res => {
						queryParams.value.sessionKey = res.data.data
						let query = {
							...queryParams.value,
							type: '5',
							userType: '1',
							invitationCode: uni.getStorageSync('SCENE'),
						}
						console.log('注册请求参数', query)
						showLogin.value = false
						// 注册登录
						loginApi(query)
					})
				},
				fail: err=>{
					console.log('err', err)
				}
			});
		} else {
			
			proxy.tui.toast('获取手机号失败')
		}
	}
	// 直接登录 or 弹框注册后登录
	function ToLogin(){
		uni.login({
			provider: 'weixin',
			success: res => {
				// 通过code调用获取openid接口 查询是否已注册
				// 如果已注册，直接获取用户信息
				proxy.api.getWxOpenId({code: res.code}).then(res => {
					let resData = res.data.data
					//已注册 
					if(resData.isTrue==1){  
						let query = {
							openid: resData.user ?. wechatAppletOpenid,
							type: '5',
							userType: '1',
						}
						loginApi(query)
					}else if(resData.isTrue==0){  
						queryParams.value.openid = resData.openid
						showLogin.value = true
					}else {
						proxy.tui.toast('返回数据有误，请重试')
					}
				})
			},
			fail: err=>{
				console.log('err', err)
			}
		});
		
	}
</script>

<style lang="scss" scoped>
	.avatar-wrapper {
		padding: 0;
		margin: 0;
		width: 60rpx;
		height: 60rpx;
		background-color: raga(0, 0, 0, 0);
	}
	
	.argeement {
		margin-top: 88rpx;
		width: 100%;
		padding: 0 40rpx;
		line-height: 40rpx;
		letter-spacing: 3rpx;
		image {
			width: 32rpx;
			height: 32rpx;
			margin-right: 10rpx;
		}
		.texts{
			text:nth-child(1) {
				@include str(28rpx, 500, #333);
			}
			text:nth-child(2) {
				@include str(28rpx, 500, $uni-color-primary);
			}
			text:nth-child(3) {
				@include str(28rpx, 500, $uni-color-primary);
			}
		}
	}
	
	.container {
		border-top: 1rpx solid #f4f4f4;
		width: 100%;
		background-color: #fff;
		.content {
			.btn{
				margin-top: 118rpx;
				width: 690rpx;
				height: 88rpx;
				background: rgba(59,140,220,1);
				border-radius: 16rpx;
				@include str(30rpx, 500, #fff);
				line-height: 42rpx;
			}
		}
	}
</style>